package com.zy.fee.roadpark.activity.nb;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.printer.sdk.Barcode;
import com.printer.sdk.PrinterConstants;
import com.spd.print.jx.impl.PrintImpl;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.adapter.NbPayBackAdapter;
import com.zy.fee.roadpark.app.AppApplication;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.NbNodeRecordLogic;
import com.zy.fee.roadpark.model.M_CarNumber;
import com.zy.fee.roadpark.model.M_NodeRecord;
import com.zy.fee.roadpark.model.apimodel.APIM_CarNumberList;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.Convert;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.ListUtils;
import com.zygk.library.util.PreferencesHelper;
import java.util.ArrayList;
import java.util.List;

import static com.printer.sdk.PrinterConstants.BarcodeType.DATAMATRIX;
import static com.printer.sdk.PrinterConstants.BarcodeType.PDF417;

/**
 * Created by Wikison on 2019/4/3.
 * 补缴单据列表
 */
public class NbPayBackListActivity extends BaseActivity {
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.tv_hint) TextView tvHint;
  @BindView(R.id.listView) ListView listView;

  private NbPayBackAdapter payBackAdapter;
  private List<M_CarNumber> carNumberList = new ArrayList<>();

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_nb_pay_back_list);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    registerReceiver(new String[] { Constants.BROADCAST_REFRESH_OVERPAY_BILL_LIST });

    payBackAdapter = new NbPayBackAdapter(mContext, carNumberList);
    listView.setAdapter(payBackAdapter);

    nbnode_record_history_admin_list();
  }

  private void initView() {
    lhTvTitle.setText("补缴单据列表");
  }

  private void initListener() {
    payBackAdapter.setOnPrintClickListener(mCarNumber -> {
      CommonDialog.showYesOrNoDialog(mContext, "是否打印补缴汇总单", "是", "否", ()->{
      }, ()->{
        printMainTicket(mCarNumber);
      });
    });
  }

  private void nbnode_record_history_admin_list() {
    NbNodeRecordLogic.nbnode_record_histroy_admin_list(mContext, new HttpRequest.HttpCallback() {
      @Override public void onStart() {
        showPd();
      }

      @Override public void onSucceed(Object obj) {
        APIM_CarNumberList result = (APIM_CarNumberList) obj;
        if (ListUtils.isEmpty(result.getCarNumberList())) {
          tvHint.setVisibility(View.VISIBLE);
          listView.setVisibility(View.GONE);
        } else {
          tvHint.setVisibility(View.GONE);
          listView.setVisibility(View.VISIBLE);
          payBackAdapter.setData(result.getCarNumberList());
        }
      }

      @Override public void onFailed() {

      }

      @Override public void onFinish() {
        dismissPd();
      }
    });
  }

  @Override protected void handleReceiver(Context context, Intent intent) {
    super.handleReceiver(context, intent);
    if (intent == null || TextUtils.isEmpty(intent.getAction())) {
      return;
    }
    if (Constants.BROADCAST_REFRESH_OVERPAY_BILL_LIST.equals(intent.getAction())) {
      nbnode_record_history_admin_list();
    }
  }

  private void printMainTicket(M_CarNumber mCarNumber) {
    try {
      PrintImpl mPrinter = AppApplication.getPrinterImpl();
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 1, 1, 0, 0);
      StringBuilder sb = new StringBuilder();
      sb.append("欠费追缴告知单");
      sb.append("\n");
      sb.append("（汇总）");
      mPrinter.printText(sb.toString());

      mPrinter.setPrinter(1, 1);
      mPrinter.setPrinter(2, 0);

      sb = new StringBuilder();
      sb.append("车牌号:   " + mCarNumber.getCarNumber());
      sb.append("\n");
      sb.append(
          "追缴路段: " + preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_NAME));
      sb.append("\n");
      sb.append("欠费笔数:   " + mCarNumber.getNodeRecordList().size());
      sb.append("\n");
      double money = 0;
      for (M_NodeRecord nodeRecord : mCarNumber.getNodeRecordList()) {
        money += nodeRecord.getMoney();
      }
      sb.append(
          "欠费金额:   " + Convert.getMoneyString3(money));
      sb.append("\n");
      sb.append("追缴时间:   " + DateTimeUtil.getCurrentTime());
      sb.append("\n");
      sb.append("收款单位:   " + "尚盈车联");
      sb.append("\n");
      sb.append("交费查询电话:   " + AppApplication.instance().parkTelephone);
      sb.append("\n");
      sb.append("1.免责声明：请遵守《交通法》第56条之规定，一车一位，线内顺向停放。停车期间车辆发生碰擦及车内财物的丢失需要自行承担。");
      sb.append("\n");
      sb.append("2.温馨提示：停车照片已上传取证，请及时缴费，欠费行为将被计入个人诚信系统，将对您后期的停车权益造成影响。");
      sb.append("\n");
      sb.append("\n");

      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.setPrinter(2, 0);
      mPrinter.printText(sb.toString());

      String url =
          "https://www.ychel.com/pay?state=carnum";

      Barcode barcode;
      int[] width = new int[] { 0, 1, 0 };
      int[] height = new int[] { 76, 0, 8 };
      byte[] bytes = new byte[] { PrinterConstants.BarcodeType.QRCODE, PDF417, DATAMATRIX };
      barcode = new Barcode(bytes[0], width[0], height[0], 6, url);
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.printBarCode(barcode);
      mPrinter.setPrinter(1, 1);

      sb = new StringBuilder();
      sb.append("微信支付宝扫码自助缴费");
      sb.append("\n");
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.printText(sb.toString());

      sb = new StringBuilder();
      sb.append("\n");
      sb.append("\n");
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 1, 1, 0, 0);
      mPrinter.printText(sb.toString());
      mPrinter.setPrinter(1, 2);

      Thread.sleep(3000);

      CommonDialog.showYesOrNoDialog(mContext, "是否继续打印追缴明细", "是", "否", () -> {
      }, () -> {
        //打印明细
        printListTicket(mCarNumber);
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void printListTicket(M_CarNumber mCarNumber) {
    try {
      PrintImpl mPrinter = AppApplication.getPrinterImpl();
      mPrinter.setPrinter(2, PrinterConstants.Command.ALIGN_CENTER);
      mPrinter.setFont(0, 1, 1, 0, 0);
      StringBuilder sb = new StringBuilder();
      sb.append("欠费追缴告知单");
      sb.append("\n");
      sb.append("（明细）");
      mPrinter.printText(sb.toString());

      mPrinter.setPrinter(1, 1);

      mPrinter.setPrinter(2, 0);

      sb = new StringBuilder();
      sb.append("车牌号:   " + mCarNumber.getCarNumber());
      sb.append("\n");
      sb.append(
          "追缴路段: " + preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_NAME));
      sb.append("\n");
      sb.append("打印时间:   " + DateTimeUtil.getCurrentTime());
      sb.append("\n");
      for (M_NodeRecord nodeRecord : mCarNumber.getNodeRecordList()) {
        sb.append("-----------------------------");
        sb.append("\n");
        sb.append(nodeRecord.getLotName());
        sb.append("\n");
        sb.append("驶入时间:   " + nodeRecord.getStartTime());
        sb.append("\n");
        sb.append("停车时长:   " + nodeRecord.getMin() + "分钟");
        sb.append("\n");
        sb.append("追缴金额:   " + Convert.getMoneyString3(nodeRecord.getMoney()));
        sb.append("\n");
      }

      sb.append("\n");
      sb.append("\n");
      sb.append("\n");

      // 字号使用默认
      mPrinter.setFont(0, 0, 0, 0, 0);
      mPrinter.setPrinter(2, 0);

      mPrinter.printText(sb.toString());
      // 打印
      //mPrinter.printText(sb.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @OnClick({
      R.id.ll_back
  }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
    }
  }
}
